package com.sicilin.common.json.date;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsDateJsonValueProcessor;
import net.sf.json.processors.JsonBeanProcessor;
import net.sf.json.processors.JsonValueProcessor;

import java.sql.Date;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;


/**
 * Created by peizangpin on 2017/5/23.
 */
public class DateUtils {

    /**
     * 提供一个JSON特定转换部分时间类的JsonConfig <br/>
     *     java.util.Date <br/>
     *     java.sql.Date <br/>
     *     java.sql.Timestamp <br/>
     * @return
     */
    public static JsonConfig getDateJSONConfig(){
        JsonConfig jc = new JsonConfig();
        jc.registerJsonValueProcessor(Timestamp.class,getTimeJsonValueProcessor());
        jc.registerJsonValueProcessor(Date.class,getTimeJsonValueProcessor());
        jc.registerJsonValueProcessor(java.util.Date.class,getTimeJsonValueProcessor());
        return jc;
    }

    /**
     * 提供一个JSON特定转换部分时间类的JsonConfig(主要用于JavaScript易操作) <br/>
     *     java.util.Date <br/>
     *     java.sql.Date <br/>
     *     java.sql.Timestamp <br/>
     * @return
     */
    public static JsonConfig getJsDateJSONConfig(){
        JsonConfig jc = new JsonConfig();
        jc.registerJsonValueProcessor(Timestamp.class,new JsDateJsonValueProcessor());
        jc.registerJsonValueProcessor(Date.class,new JsDateJsonValueProcessor());
        jc.registerJsonValueProcessor(java.util.Date.class,new JsDateJsonValueProcessor());
        return jc;
    }

    /**
     * 针对特定时间类的转换成JsonValue为 yyyy-MM-dd HH:mm:ss的String格式<br/>
     * 该方法只允许该类内部使用<br/>
     * 转换类:<br/>
     *     java.util.Date <br/>
     *     java.sql.Date <br/>
     *     java.sql.Timestamp <br/>
     * @return
     */
    private static JsonValueProcessor getTimeJsonValueProcessor(){
        return new JsonValueProcessor() {
            public Object processArrayValue(Object bean, JsonConfig jsonConfig) {
                if(bean == null){return null;}
                return this.changeToString(bean);
            }

            public Object processObjectValue(String s, Object bean, JsonConfig jsonConfig) {
                if(bean == null){return null;}
                return this.changeToString(bean);
            }

            private String changeToString(Object bean){
                if(bean == null){return null;}
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Class clzz = bean.getClass();
                if(clzz.equals(Timestamp.class)
                        || clzz.equals(Date.class)
                        || clzz.equals(java.util.Date.class) ){
                    return sdf.format(bean);
                }
                return bean.toString();
            }
        };
    }
}
